/*
	DataBase Query parsing RPC server implementations
*/

#include <mysql/mysql.h>
#include <stdlib.h>
#include "datab.h"

char *send_query( QUERY *rcv, struct svc_req *req){

	MYSQL *db;
	MYSQL_RES *result;
	MYSQL_ROW row;
	int num;
	int i;
	int count = 0;
	char *answer;


	db = mysql_init(NULL);

	if( db == NULL ){
		printf("Error Creating Data Base[%u]: %s \n", mysql_errno(db), mysql_errno(db) );
		exit(1);
	}

	if( mysql_real_connect( db, "localhost", "user", "passwd", "database", 0 , NULL, 0) ==  NULL ){
		printf("Error Connecting to Data Base[%u]: %s\n", mysql_errno(db), mysql_errno(db) );
		exit(1);
	}

	if( mysql_query( db, rcv->query ) == NULL ){
		printf("Error Sending[%u]: %s\n", mysql_errno(db), mysql_errno(db) );
		exit(1);
	}

	result = mysql_store_result(db);

	num = mysql_num_fields(result);

	while( ( row = mysql_fetch_row(result) ) ){
		
		for( i = 0; i < num; i++ ){
			count += strlen(row[i]);
			realloc( answer, sizeof(char)*count );
			memcpy( answer[ count-strlen(row[i]) ], row[i], sizeof(char)*strlen(row[i]) );
		}
	}

	mysql_free_result(result);
	mysql_close(db);

	return answer;
}
